<?php
/*
  Plugin Name: Seoul Menu  
  Plugin URI: http://www.epart.com/
  Description: 메뉴관리에 이미지 추가하는 플러그인.
  Version: 0.1.1
  Author: Epart E-Business Development Team
  Author URI: http://www.epart.com/
  License: Epart BBS plugin follows Word Press License Terms.
*/
if (is_admin ()) {
    
    $pluginUrl = trailingslashit(WP_PLUGIN_URL) . dirname(plugin_basename(__FILE__));
    
    // 메뉴관리에서 사용할 스크립트 추가한다.
    if( basename($_SERVER['PHP_SELF']) == "nav-menus.php" ){                
        wp_enqueue_script('seoul-menu-admin-js', plugin_dir_url(__FILE__) . 'js/seoul-menu-admin.js', array('jquery'));        
        wp_localize_script("seoul-menu-admin-js", "SeoulMenuSettings", array(
            "seoul_menu_plugin_url" => $pluginUrl              
        ));
    }
    
    add_action("delete_post", "seoul_menu_delete");
    
    /**
     * 메뉴삭제시 파일과 추가 메타데이터 삭제한다
     *
     * @author bskim
     * @param string post id
     * @since 0.1
     * @return none.
     */
    function seoul_menu_delete($pid){
        $file_path = trailingslashit(WP_PLUGIN_DIR) . dirname(plugin_basename(__FILE__))."/files/";        
        $temp_post = get_post($pid);
        if( $temp_post->post_type == "nav_menu_item" ){            
            $menu_image1_src = get_post_meta($temp_post->ID, "_menu_image1_src");
            $menu_image2_src = get_post_meta($temp_post->ID, "_menu_image2_src");
            
            if( isset($menu_image1_src[0]) &&  $menu_image1_src[0] != ""){
                @unlink( $file_path.$menu_image1_src[0] );
                delete_post_meta($temp_post->ID, "_menu_image1_src");
            }
            
            if( isset($menu_image2_src[0]) &&  $menu_image2_src[0] != ""){
                @unlink( $file_path.$menu_image2_src[0] );
                delete_post_meta($temp_post->ID, "_menu_image2_src");
            }
            delete_post_meta($temp_post->ID, "_menu_type");                        
        }
        
    }
}else{
    
    wp_enqueue_script('seoul-menu-user-js', plugin_dir_url(__FILE__) . 'js/seoul-menu-user.js', array('jquery')); 
    
    /**
     * wp_nav_menu 함수 대체
     *
     * @author bskim
     * @param array wp_nav_menu 함수 형식 그대로 인자 배열로 받음
     * @since 0.1
     * @return array 옵션별로 직접 화면에 뿌리거나 메뉴 객체 배열 리턴한다.
     */
    function seoul_nav_menu( $args = array() ) {
	static $menu_id_slugs = array();

	$defaults = array( 'menu' => '', 'container' => 'div', 'container_class' => '', 'container_id' => '', 'menu_class' => 'menu', 'menu_id' => '',
	'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
	'depth' => 0, 'walker' => '', 'theme_location' => '' );

	$args = wp_parse_args( $args, $defaults );
	$args = apply_filters( 'wp_nav_menu_args', $args );
	$args = (object) $args;

	// Get the nav menu based on the requested menu
	$menu = wp_get_nav_menu_object( $args->menu );

	// Get the nav menu based on the theme_location
	if ( ! $menu && $args->theme_location && ( $locations = get_nav_menu_locations() ) && isset( $locations[ $args->theme_location ] ) )
		$menu = wp_get_nav_menu_object( $locations[ $args->theme_location ] );

	// get the first menu that has items if we still can't find a menu
	if ( ! $menu && !$args->theme_location ) {
		$menus = wp_get_nav_menus();
		foreach ( $menus as $menu_maybe ) {
			if ( $menu_items = wp_get_nav_menu_items($menu_maybe->term_id) ) {
				$menu = $menu_maybe;
				break;
			}
		}
	}

	// If the menu exists, get its items.
	if ( $menu && ! is_wp_error($menu) && !isset($menu_items) ){
		$menu_items = wp_get_nav_menu_items( $menu->term_id );             
        }
       
       // 메뉴 이미지 설정시 이미지로 교체한다. 
       foreach( $menu_items as $menu_item ){
           
           $menu_type = get_post_meta($menu_item->ID, "_menu_type");
           if( isset($menu_type[0]) && $menu_type[0] == "image"){               
               $menu_image1_src = get_post_meta($menu_item->ID, "_menu_image1_src");
               $menu_image2_src = get_post_meta($menu_item->ID, "_menu_image2_src");
               $test_title = $menu_item->title;
               if(isset($menu_image1_src[0]) && isset($menu_image2_src[0])){
                    $menu_item->title ='<img src="'.WP_PLUGIN_URL."/seoul-menu/files/".$menu_image1_src[0].'" alt="'.$test_title.'" title="'.$test_title.'" class="exist-over-image" />';
               } else if(isset($menu_image1_src[0])){
                    $menu_item->title ='<img src="'.WP_PLUGIN_URL."/seoul-menu/files/".$menu_image1_src[0].'" alt="'.$test_title.'" title="'.$test_title.'" />';                   
               }
           }
       } 

	// If no menu was found or if the menu has no items and no location was requested, call the fallback_cb if it exists
	if ( ( !$menu || is_wp_error($menu) || ( isset($menu_items) && empty($menu_items) && !$args->theme_location ) )
		&& $args->fallback_cb && is_callable( $args->fallback_cb ) )
			return call_user_func( $args->fallback_cb, (array) $args );

	// If no fallback function was specified and the menu doesn't exists, bail.
	if ( !$menu || is_wp_error($menu) )
		return false;

	$nav_menu = $items = '';

	$show_container = false;
	if ( $args->container ) {
		$allowed_tags = apply_filters( 'wp_nav_menu_container_allowedtags', array( 'div', 'nav' ) );
		if ( in_array( $args->container, $allowed_tags ) ) {
			$show_container = true;
			$class = $args->container_class ? ' class="' . esc_attr( $args->container_class ) . '"' : ' class="menu-'. $menu->slug .'-container"';
			$id = $args->container_id ? ' id="' . esc_attr( $args->container_id ) . '"' : '';
			$nav_menu .= '<'. $args->container . $id . $class . '>';
		}
	}
       
	// Set up the $menu_item variables
	_wp_menu_item_classes_by_context( $menu_items );

	$sorted_menu_items = array();
	foreach ( (array) $menu_items as $key => $menu_item )
		$sorted_menu_items[$menu_item->menu_order] = $menu_item;

	unset($menu_items);

	$sorted_menu_items = apply_filters( 'wp_nav_menu_objects', $sorted_menu_items, $args );

	$items .= walk_nav_menu_tree( $sorted_menu_items, $args->depth, $args );
	unset($sorted_menu_items);

	// Attributes
	if ( ! empty( $args->menu_id ) ) {
		$wrap_id = $args->menu_id;
	} else {
		$wrap_id = 'menu-' . $menu->slug;
		while ( in_array( $wrap_id, $menu_id_slugs ) ) {
			if ( preg_match( '#-(\d+)$#', $wrap_id, $matches ) )
				$wrap_id = preg_replace('#-(\d+)$#', '-' . ++$matches[1], $wrap_id );
			else
				$wrap_id = $wrap_id . '-1';
		}
	}
	$menu_id_slugs[] = $wrap_id;

	$wrap_class = $args->menu_class ? $args->menu_class : '';

	// Allow plugins to hook into the menu to add their own <li>'s       
	$items = apply_filters( 'wp_nav_menu_items', $items, $args );
	$items = apply_filters( "wp_nav_menu_{$menu->slug}_items", $items, $args );


	$nav_menu .= sprintf( $args->items_wrap, esc_attr( $wrap_id ), esc_attr( $wrap_class ), $items );
       
        
	unset( $items );

	if ( $show_container )
		$nav_menu .= '</' . $args->container . '>';

	$nav_menu = apply_filters( 'wp_nav_menu', $nav_menu, $args );

	if ( $args->echo ){
		echo $nav_menu;
        }else{
		return $nav_menu;
        }
    }
}
?>
